package com.evil.application.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.evil.application.pojo.entity.ApplicationPackage;
import com.evil.common.application.util.ApplicationRedisKeyUtil;
import com.evil.common.core.constant.RedisConstant;
import com.evil.common.core.enums.RCodeEnum;
import com.evil.common.core.exception.BusinessException;
import com.evil.common.core.util.CacheMapperUtil;
import com.evil.common.core.util.StreamUtil;
import org.apache.ibatis.annotations.Param;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 应用包表
 *
 * @author liyang
 * @date 2023-02-15 16:02
 */
public interface ApplicationPackageMapper extends BaseMapper<ApplicationPackage> {

    Optional<ApplicationPackage> isExistById(Long id);

    default Optional<ApplicationPackage> isExistById_Cache(Long id) {
        return CacheMapperUtil.cacheById(
                id,
                ApplicationPackage.class,
                this::findById,
                ApplicationRedisKeyUtil::requestUuidPackageKey,
                RedisConstant.REQUEST_UUID_EXPIRE_IN_SECOND
        );
    }

    default ApplicationPackage findById(Long id) {
        return this.isExistById(id).orElseThrow(() -> new BusinessException(RCodeEnum.USER_NOT_EXIST));
    }

    default ApplicationPackage findById_Cache(Long id) {
        return this.isExistById(id).orElseThrow(() -> new BusinessException(RCodeEnum.USER_NOT_EXIST));
    }

    List<ApplicationPackage> findByIds(@Param("ids") Collection<Long> ids, @Param("filterDeleted") boolean filterDeleted);

    default List<ApplicationPackage> findByIds_Cache(Collection<Long> ids, boolean filterDeleted) {
        return CacheMapperUtil.cacheByIds(
                ids,
                filterDeleted,
                ApplicationPackage.class,
                this::findByIds,
                ApplicationPackage::getPackageId,
                ApplicationPackage::getIsDeleted,
                null,
                ApplicationRedisKeyUtil::requestUuidPackageKeyMap,
                RedisConstant.REQUEST_UUID_EXPIRE_IN_SECOND
        );
    }

    List<ApplicationPackage> findByEnterpriseId(Long enterpriseId);

    default Map<Long, ApplicationPackage> findMapByIds(Collection<Long> ids, boolean filterDeleted) {
        return StreamUtil.toMapK(this.findByIds(ids, filterDeleted), ApplicationPackage::getPackageId);
    }

    int findMaxSortByEnterpriseId(Long enterpriseId);
}